package cn.lanqiao.chart;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class TestSockClient {
    public static void main(String[] args) {

        DataOutputStream dos = null;
        Socket socket = null;

        Scanner input = new Scanner(System.in);
        String msg = null;
        try {
            //建立连接
            socket = new Socket("localhost", 8888);
            dos = new DataOutputStream(socket.getOutputStream());

            //建立子线程用于接收信息
            final Socket FINAL_SOCKET = socket;
            new Thread() {
                @Override
                public void run() {
                    String s = null;
                    DataInputStream dis = null;
                    try {
                        dis = new DataInputStream(FINAL_SOCKET.getInputStream());
                        while(((s = dis.readUTF()) != null)){
                            System.out.println(s);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();

            //main线程，完成客户端向服务器端发送请求的操作
            do {
                System.out.print("我说：");
                msg = input.next(); //阻塞
                dos.writeUTF(msg);
            } while (!("88").equals(msg));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            try {
                dos.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
